package com.onetech.adrewards.free.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jp.co.CAReward_Media.CARMCommon;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.onetech.adrewards.free.R;
import com.onetech.adrewards.free.OneTech_ApplicationContext;
import com.onetech.adrewards.free.config.AppConfig;
import com.onetech.adrewards.free.config.AppConfig.Cache;
import com.onetech.adrewards.free.dialogs.InfoDialog;
import com.onetech.adrewards.free.models.CommonModel;
import com.onetech.adrewards.free.objects.DeviceInfoDTO;
import com.zuzu.db.store.SQLiteStore;
import com.zuzu.db.store.SimpleStoreIF;

public class AdrewadsUtils {
	public static String convert2SHA1(String data)
	{
	    String sha1 = "";
	    try
	    {
	        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
	        crypt.reset();
	        crypt.update(data.getBytes("UTF-8"));
	        sha1 = byteToHex(crypt.digest());
	    }
	    catch(NoSuchAlgorithmException e)
	    {
	        e.printStackTrace();
	    }
	    catch(UnsupportedEncodingException e)
	    {
	        e.printStackTrace();
	    }
	    return sha1;
	}

	public static String byteToHex(final byte[] hash)
	{
	    Formatter formatter = new Formatter();
	    for (byte b : hash)
	    {
	        formatter.format("%02x", b);
	    }
	    String result = formatter.toString();
	    formatter.close();
	    return result;
	}
	public static int convertString2Int(String value){
		try {
			return Integer.valueOf(value);
		} catch (Exception e) {
			return 0;
		}
	}
	public static boolean checkCurrentVersion(Context context,String targetVersion){
		boolean result=false;
		try {
			String currentVersion=getVersionName(context);
			if(targetVersion.trim().equals(currentVersion.trim())){
				result=true;
			}
		} catch (Exception e) {			
		}
		return result;
	}
	public static void checkUId(){		
		try {
			if(AppConfig.uId!=null && AppConfig.uId.trim().length()>0){
				return;
			}
			String uId=CommonModel.getInstance().getStore(Cache.ONE_TECH_USER_ID);
			if(uId!=null){
				AppConfig.uId=uId;
			}
		} catch (Exception e) {
		}
	}
	public static String getStore(Context context,String key){
		String result=null;
		try {			
			SharedPreferences sharedpreferences = context.getSharedPreferences(Cache.ONE_TECH_SHAREPREFENCE, Context.MODE_PRIVATE);				
			result=sharedpreferences.getString(key, null);
			if(result!=null && result.trim().length()<1){
				return null;
			}
		} catch (Exception e) {
			return null;
		}
		return result;
	}
	public static void setStore(Context context,String key,String value){
		try {			
			SharedPreferences sharedpreferences = context.getSharedPreferences(Cache.ONE_TECH_SHAREPREFENCE, Context.MODE_PRIVATE);				
			Editor editor=sharedpreferences.edit();
			editor.putString(key, value);
			editor.commit();
		} catch (Exception e) {
			return;
		}
		return;
	}
	public static void getUIDFromStore(Context context){
		String uId=AdrewadsUtils.getUserId(context, true, null);
		if(uId!=null && uId.trim().length()>0){
			AppConfig.uId=uId;
		}
	}
	public static String getUserId(Context context,boolean isGet,String uid){
		String result="";						
		if(isGet){
			result=getStore(context, Cache.ONE_TECH_USER_ID);				
		}else{
			setStore(context, Cache.ONE_TECH_USER_ID, uid);				
		}		
		return result;
	}
	public static void setFirstStartUp(boolean isStarUpReady){
		try {		
			SharedPreferences sharedpreferences = OneTech_ApplicationContext.getContext().getSharedPreferences(Cache.ONE_TECH_SHAREPREFENCE, Context.MODE_PRIVATE);
			Editor editor=sharedpreferences.edit();
			editor.putBoolean(Cache.ONE_TECH_FIRST_START_UP_FLAG, isStarUpReady);
			editor.commit();
			
		} catch (Exception e) {
		}
	}
	public static boolean checkStartUp(Activity activity){
		try {			
			SharedPreferences sharedpreferences = activity.getSharedPreferences(Cache.ONE_TECH_SHAREPREFENCE, Context.MODE_PRIVATE);
			
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());
	    	Calendar calendar1 = Calendar.getInstance();
	    	Calendar calendar2 = Calendar.getInstance();

	    	String currentDateTime = dateFormat.format(new Date());
	    	String lastDate=sharedpreferences.getString(Cache.ONE_TECH_LAST_USE, "");
	    	String uId=sharedpreferences.getString(Cache.ONE_TECH_USER_ID, "");
	    	boolean isFirstStartUpReady=sharedpreferences.getBoolean(Cache.ONE_TECH_FIRST_START_UP_FLAG, false);
	    	if(lastDate.trim().length()<1 || uId.trim().length()<1 || (!isFirstStartUpReady)){
	    		Editor editor=sharedpreferences.edit();
		    	editor.putString(Cache.ONE_TECH_LAST_USE, currentDateTime);
		    	editor.commit();
	    		return true;
	    	}
//	    	System.out.println("Compare Result : " + lastDate);
//	    	System.out.println("Compare Result : " + currentDateTime);
	    	
	    	Date date1 = dateFormat.parse(lastDate);
	    	Date date2 = dateFormat.parse(currentDateTime);
	    	
	    	calendar1.setTime(date1);
	    	calendar2.setTime(date2);
	    	
	    	int result= calendar2.compareTo(calendar1);
	    	boolean result2=(result>0)?true:false; 
	    	//if(result>0){
    		Editor editor=sharedpreferences.edit();
	    	editor.putString(Cache.ONE_TECH_LAST_USE, currentDateTime);
	    	editor.commit();
	    	//}	    	
	    	return result2;
	    	
		} catch (Exception e) {			
			return false;
		}
	}
	public static String getChargeTypeText(Context activity,String charge_type){
		try {
			int chargeType=Integer.valueOf(charge_type);
			String result="";
			switch (chargeType) {
			case 1:
				result=activity.getString(R.string.charge_type_text_1);
				break;
			case 2:
				result=activity.getString(R.string.charge_type_text_2);
				break;
			case 3:
				result=activity.getString(R.string.charge_type_text_3);			
				break;
			default:
				return "";				
			}
			return result;
		} catch (Exception e) {
				return "";
		}
	}
	public static String getAction_Cate_ID_Text(Context activity,String action_cate_id){
		try {
			int action=Integer.valueOf(action_cate_id);
			String result=" | ";
			switch (action) {
			case 3:
				result+=activity.getString(R.string.action_cate_id_3);
				break;
			case 4:
				result+=activity.getString(R.string.action_cate_id_4);
				break;
			case 5:
				result+=activity.getString(R.string.action_cate_id_5);
				break;
			case 6:
				result+=activity.getString(R.string.action_cate_id_6);
				break;
			case 7:
				result+=activity.getString(R.string.action_cate_id_7);
				break;
			case 9:
				result+=activity.getString(R.string.action_cate_id_9);
				break;
			case 10:
				result+=activity.getString(R.string.action_cate_id_10);
				break;
			default:
				return "";				
			}
			return result;
		} catch (Exception e) {
				return "";
		}
	}
	public static void go2Web(Context mContext,String url) {
		Intent launchIntent = null;
		try {
			launchIntent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
			launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			mContext.startActivity(launchIntent);
		} catch (android.content.ActivityNotFoundException anfe) {
			return;
		}

	}

	@SuppressLint("SimpleDateFormat")
	public static String dateFormat(String dateTime) {
		try {
			/*
			 * String[] date = dateTime.trim().split(" "); String[] arrDate =
			 * date[0].split("-"); String[] time = date[1].split(":");
			 * 
			 * String strDate = arrDate[0] + "/" + arrDate[1] + "/" + arrDate[2]
			 * + " " + time[0] + ":" + time[1]; return strDate;
			 */
			SimpleDateFormat curFormater = new SimpleDateFormat(
					"yyyy-MM-dd hh:mm:ss");
			Date dateObj = curFormater.parse(dateTime);
			SimpleDateFormat postFormater = new SimpleDateFormat(
					"yyyy/MM/dd hh:mm");

			String newDateStr = postFormater.format(dateObj);
			return newDateStr;
		} catch (Exception e) {
			return null;
		}
	}

	private String getChargeType(String _charge_type) {
		final String[] items = OneTech_ApplicationContext.getContext()
				.getResources().getStringArray(R.array.charge_type_names);
		try {
			int charge_type = Integer.valueOf(_charge_type);
			return items[charge_type];
		} catch (Exception e) {
			return items[0];
		}
	}

	public static SimpleStoreIF getStoreAdapter(String name, Context mContext,
			int items) {
		return SQLiteStore.getInstance(name, mContext, AppConfig.DBVERSION,
				items);
	}

	public static void showInfoDialog(Context context, String title,
			String message) {
		try {
			InfoDialog mInfoDialog = new InfoDialog(context, title, message);
			mInfoDialog.show();
		} catch (Exception e) {
			return;
		}
	}

	public static void showMessage(Context context, String message) {
		Toast.makeText(context, message, Toast.LENGTH_LONG).show();
	}

	public static boolean isOnline(Context c) {
		ConnectivityManager cm = (ConnectivityManager) c
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if (ni != null && ni.isConnected())
			return true;
		else
			return false;
	}

	public static boolean validateEmail(String email) {
		Pattern pattern;
		Matcher matcher;
		String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
				+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		pattern = Pattern.compile(EMAIL_PATTERN);
		matcher = pattern.matcher(email);
		return matcher.matches();

	}

	public static String getCrypt() {
		CARMCommon common = new CARMCommon();
		String crypt = null;

		try {
			checkUId();
			crypt = common.encodeSHA1(AppConfig.uId + AppConfig.apiKey);
		} catch (Exception e) {
			Log.d("Gen crypt", "crypt failre");
			crypt = "";
		}

		return crypt;
	}

	public static String getVersionName(Context c) {
		try {
			return c.getPackageManager().getPackageInfo(c.getPackageName(), 0).versionName;
		} catch (Exception e) {
			return null;
		}
	}

	public static String getPackageName(Context c) {
		try {
			return c.getPackageManager().getPackageInfo(c.getPackageName(), 0).packageName;
		} catch (Exception e) {
			return null;
		}
	}

	public static DeviceInfoDTO getDeviceInfo() {
		DeviceInfoDTO result = null;
		try {
			String android_id = Secure.getString(OneTech_ApplicationContext
					.getContext().getContentResolver(), Secure.ANDROID_ID);
			TelephonyManager TelephonyMgr = (TelephonyManager) OneTech_ApplicationContext
					.getContext().getSystemService(Context.TELEPHONY_SERVICE);
			String imei = TelephonyMgr.getDeviceId(); // Requires
			String device_type = android.os.Build.DEVICE;
			String serial_number = android.os.Build.SERIAL;
			String app_version = getVersionName(OneTech_ApplicationContext
					.getContext());
			String packag_ename = getPackageName(OneTech_ApplicationContext
					.getContext());

			result = new DeviceInfoDTO();
			result.setDevice_Id(android_id);
			result.setImei(imei);
			result.setSerial_Number(serial_number);
			result.setDevice_Type(device_type);
			result.setApp_Version(app_version);
			result.setApp_Id(packag_ename);
		} catch (Exception e) {

		}
		return result;
	}

	public static void loadDeviceInfo() {
		if (AppConfig.deviceInfo == null) {
			AppConfig.deviceInfo = getDeviceInfo();
		}
	}
}
